using System;
using System.IO;

namespace HtmlToPDF.PDF
{
	/// <summary>
	/// Summary description for PDFGenerator.
	/// </summary>
	public class PDFGenerator : System.Web.UI.Page
	{
		private string sLandScape;
		private string m_sWaterMark;
		private string m_sDrive;
		private string m_Directory;
		public PDFGenerator(string sDirectory)
		{
			sFontSize = "";
			sLandScape = "--landscape";
			m_sWaterMark = "";
			string sRoot = Server.MapPath("/");
			m_sDrive = "" + sRoot[0];
			m_Directory = sDirectory;
		}

		private string sFontSize;
		public string FontSize
		{
			set { sFontSize = "--fontsize " + value; }
			get { return(sFontSize);}
		}

		public void SetLandScape(bool bRet)
		{
			if ( bRet == false )
				sLandScape = "";
		}

		public void SetWaterMark (bool bRet)
		{
			if ( bRet == false)
				m_sWaterMark = "";

		}

		public string RunWeb(string sUrl)
		{
			string sFileName = GetNewName();

			System.Diagnostics.Process	pProcess = new System.Diagnostics.Process();
			pProcess.StartInfo.FileName = m_sDrive + ":" + m_Directory + "\\ghtmldoc.exe";
			pProcess.StartInfo.Arguments = "--webpage --quiet " + sFontSize + " --bodyfont Arial " + sLandScape + " -t pdf14 -f " + sFileName + ".pdf " + sUrl;
			pProcess.StartInfo.WorkingDirectory = m_sDrive + ":" + m_Directory;
			
			pProcess.Start();
						
			return(sFileName + ".pdf");			
		}

		public string Run(string sRawUrl)
		{			
			string sFileName = GetNewName();
			string sPage = Server.MapPath("" + sFileName + ".html");			
			string sUrlVirtual = sRawUrl;
			StringWriter sw = new StringWriter();

			Server.Execute(sUrlVirtual, sw);
			
			StreamWriter sWriter = File.CreateText(sPage);
			sWriter.WriteLine(sw.ToString());
			sWriter.Close();	
			
			System.Diagnostics.Process	pProcess = new System.Diagnostics.Process();
			pProcess.StartInfo.FileName = m_sDrive + ":" + m_Directory + "\\ghtmldoc.exe";
			pProcess.StartInfo.Arguments = "--webpage --quiet " + sFontSize + m_sWaterMark + " --bodyfont Arial " + sLandScape + " -t pdf14 -f " + sFileName + ".pdf " + sFileName + ".html";
			pProcess.StartInfo.WorkingDirectory = m_sDrive + ":" + m_Directory;
			
			pProcess.Start();			
						
			return(sFileName + ".pdf");			
		}
	

		private string GetNewName()
		{
			string sName = Convert.ToString(DateTime.Now.Ticks);
			return(sName);
		}
	}
}
